package com.terren.webdig.common.util;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;

/**
 * @项目名称：报告系统
 * @类名称：StringUtil
 * @类描述：字符工具类 
 */
public class StringUtil {

	/**
	 * 去掉字符串中的空格
	 * 
	 * @param str
	 * @return
	 */
	public static String replaceBlank(String str) {
		String dest = "";
		if (str != null) {
			Pattern p = Pattern.compile("\\s*|\t|\r|\n");
			Matcher m = p.matcher(str);
			dest = m.replaceAll("");
		}
		return dest;
	}

	/**
	 * 将带有统一中文全角空格的内容替换成换行符
	 * 
	 * @param sourContent
	 * @return
	 */
	public static String newLine(String sourContent) {

		String[] strs = sourContent.split("　");
		StringBuilder sb = new StringBuilder("");
		for (String str : strs) {
			if (!"".equals(str.trim()))
				sb.append("\\n\u3000\u3000" + StringUtil.replaceBlank(str));
		}
		return sb.toString();
	}

	/**
	 * 将带有统一空格的内容替换成换行符
	 * 
	 * @param sourContent
	 * @return
	 */
	public static String newLine2(String sourContent) {

		String[] strs = sourContent.split(" ");
		StringBuilder sb = new StringBuilder("");
		for (String str : strs) {
			if (!"".equals(str.trim()))
				sb.append("\\n\u3000\u3000" + StringUtil.replaceBlank(str));
		}
		return sb.toString();
	}

	/**
	 * 
	 * @方法功能描述: 对存在参数的输入内容进行替换操作，获无参数的完整字符串
	 * @方法名:getContent
	 * @param Element
	 *            classroot,List<Column> columns
	 * @return 无
	 * @throws 未知
	 * @参数描述 : String object
	 * @返回类型：String
	 * 
	 */
	public static String getContent(String content, Object parameter) {
		// 通过工具类获得装有格式化字段的map
		if (parameter != null) {
			Map<String, String> fieldValueMap = BeanUtil.getFieldValueMap(parameter);
			Set<String> keySet = fieldValueMap.keySet();
			for (String string : keySet) {
				if (StringUtils.contains(content, "${" + string + "}")) {
					content = StringUtils.replace(content, "${" + string + "}", fieldValueMap.get(string));
				}
			}
		}
		return content;
	}

	/**
	 * 判断一个字符串是否为数字字符串
	 */
	public static boolean isNum(String count) {
		Pattern pattern = Pattern.compile("[0-9]+.?[0-9]+");
		Matcher matcher = pattern.matcher((CharSequence) count);
		boolean flag = matcher.matches();
		return flag;
	}

	/**
	 * 把一个String类型的集合转换为Integer类型的集合
	 * 
	 * @param 1,2,3,4,5
	 * @param ,
	 * @return [1,2,3,4,5]
	 */
	public static List<Integer> getIntegerListByString(String str, String symbol) {
		if (str == null || str.trim().equals("")) {
			return null;
		}

		String[] sarr = str.split(symbol);
		Integer[] iarr = new Integer[sarr.length];
		for (int i = 0; i < sarr.length; i++) {
			iarr[i] = Integer.parseInt(sarr[i]);
		}
		return Arrays.asList(iarr);
	}

	/**
	 * 类型转换
	 */
	public static Object castString(String value, Class<?> cls) {
		String name = cls.getSimpleName();
		Object cast = value;
		if(!"".equals(cast)){
			if (name.equalsIgnoreCase("Integer")) {
				cast = Integer.parseInt(cast.toString());
			}
			if (name.equalsIgnoreCase("Long")) {
				cast = Long.parseLong(cast.toString());
			}
			if (name.equalsIgnoreCase("Short")) {
				cast = Short.parseShort(cast.toString());
			}
			if (name.equalsIgnoreCase("Float")) {
				cast = Float.parseFloat(cast.toString());
			}
			if (name.equalsIgnoreCase("Double")) {
				cast = Double.parseDouble(cast.toString());
			}
			if (name.equalsIgnoreCase("Boolean")) {
				cast = Boolean.parseBoolean(cast.toString());
			}
		}else{
			cast=null;
		}
		return cast;
	}

	/**
	 * 字符串首字母大写
	 * 
	 * @param 字符串
	 * @return 首字母大写的字符串
	 */
	public static String toFirstUpperCase(String str) {
		if (str == null || str.length() < 1) {
			return "";
		}
		String start = str.substring(0, 1).toUpperCase();
		String end = str.substring(1, str.length());
		return start + end;
	}

	/**
	 * 得到时间的条件
	 * 
	 * @param 开始日期
	 * @param 结束日期
	 * @param 开始小时
	 * @param 结束小时
	 * @param 别名
	 * @return 时间条件
	 */
	public static String getWhereHour(String start, String end, Integer starthour, Integer endhour, String alias) {
		StringBuffer where = new StringBuffer("(");
		if (start != null) {
			where.append("(" + alias + ".day > '" + start + "'");
		}

		if (end != null) {
			if (!where.toString().trim().equals("")) {
				where.append(" and ");
			}
			where.append(alias + ".day < '" + end + "')");
		}

		if (start != null) {
			where.append(" or ");
			where.append("(" + alias + ".day = '" + start + "'");
			if (starthour != null) {
				where.append(" and ");
				where.append(alias + ".hour >= " + starthour);
			}
			where.append(")");
		}

		if (end != null) {
			// 开始时间和结束时间是否是同一天
			if (!start.equals(end)) {
				where.append(" or ");
			} else {
				where.append(" and ");
			}
			where.append("(" + alias + ".day = '" + end + "'");
			if (endhour != null) {
				where.append(" and ");
				where.append(alias + ".hour <= " + endhour);
			}
			where.append(")");
		}
		where.append(")");
		return where.toString();
	}

	/**
	 * 获取真实的ip地址
	 * 
	 * @param HttpServletRequest
	 * @return IP地址
	 */
	public static String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("X-Forwarded-For");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}

	/**
	 * 标题清理函数
	 */
	public static String titlecleaner(String str) {
		str = str.replaceAll("\n", "");
		str = str.replaceAll("\r", "");
		str = str.trim();
		String xnew = str.replaceAll("_新华网", "");
		int pos = xnew.lastIndexOf('_');
		if (pos != -1)
			xnew = xnew.substring(0, pos);
		return xnew.toLowerCase().trim();
	}

	/**
	 * 过滤XML
	 */
	public static String parValue(String value) {
		if (value == null) {
			return "";
		}
		value = value.replaceAll("&", "&amp;");
		value = value.replaceAll("<", "&lt;");
		value = value.replaceAll(">", "&gt;");
		value = value.replaceAll("\"", "&quot;");
		value = value.replaceAll("\'", "&apos;");
		return value;
	}

	/**
	 * 判断字符串中包含几个指定字符
	 */
	public static int countString(String src, String tar) {
		int count = 0;
		int offset = 0;
		while ((offset = src.indexOf(tar, offset)) != -1) {
			offset = offset + tar.length();
			count++;
		}
		return count;
	}

	/**
	 * 判断字符串包含的指定字符的最大index
	 */
	public static int maxIndex(String src, String tar) {
		int offset = 0;
		int index = 0;
		while ((offset = src.indexOf(tar, offset)) != -1) {
			index = offset;
			offset = offset + tar.length();
		}
		return index;
	}

	/**
	 * 替换字符串中的特殊字符
	 * 
	 * @param sourceStr
	 *            原始字符串
	 * @param replaceStr
	 *            特殊字符的替换符
	 * @return
	 */
	public static String specialFilter(String sourceStr, String replaceStr) {
		String regEx = "[`~!@#$%^&*()\\-+={}':;,\\[\\].<>/?￥%…（）_+|【】‘；：”“’。，、？\\s]";
		Pattern p = Pattern.compile(regEx);
		Matcher m = p.matcher(sourceStr);
		return m.replaceAll(replaceStr).trim();
	}

	/**
	 * 只解析url里的汉字
	 * 
	 * @param str
	 * @param charset
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public static String encodeZH(String str, String charset) throws UnsupportedEncodingException {
		String zhPattern = "^[\\u4e00-\\u9fa5]*$";
		Pattern p = Pattern.compile(zhPattern);
		StringBuffer b = new StringBuffer();
		char[] ch = str.toCharArray();
		for (char charStr : ch) {
			Matcher m = p.matcher(String.valueOf(charStr));
			while (m.find()) {
				m.appendReplacement(b, URLEncoder.encode(m.group(0), charset));
			}
			m.appendTail(b);
		}
		return b.toString();
	}
	
	// 加密
		public static String getBase64(String str) {
			byte[] b = null;
			String encoded = null;
			try {
				b = str.getBytes(StandardCharsets.UTF_8);
				if (b != null) {
					encoded = Base64.getEncoder().encodeToString(b);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			return encoded;
		}

		// 解密
		public static String getFromBase64(String s) {
			byte[] decoded = null;
			String result = null;
			if (s != null) {
				try {
					decoded = Base64.getDecoder().decode(s);
					result = new String(decoded, StandardCharsets.UTF_8);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			return result;
		}

	
	
}